package dao;

import model.User;
import utils.DBUtil;
import utils.StringUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2023/04/08  11:43
 */
public class UserDao {

    /**
     * 根据用户ID查询信息
     * @param id 用户Id
     * @return 查询到的用户信息
     */
    public User selectById(Long id){
        if(id == null){
            return null;
        }
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //获取连接
            connection = DBUtil.getConnection();
            //构造sql
            String sql = "select id,username,password from user where id = ?";
            //获取预处理对象
            statement = connection.prepareStatement(sql);
            //替换占位符
            statement.setLong(1,id);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(resultSet, statement, connection);
        }
        return null;
    }

    /**
     * 根据用户名查询信息
     * @param username 用户名
     * @return 查询到的用户信息
     */
    public User selectByUsername(String username){
        if(StringUtil.isEmpty(username)){
            return null;
        }
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //获取连接
            connection = DBUtil.getConnection();
            //构造sql
            String sql = "select id,username,password from user where username = ?";
            //获取预处理对象
            statement = connection.prepareStatement(sql);
            //替换占位符
            statement.setString(1,username);
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(resultSet, statement, connection);
        }
        return null;
    }
}
